package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.api.user.UserApi;
import com.zhentao.mapper.CdzCouponConditionMapper;
import com.zhentao.mapper.CdzCouponMapper;
import com.zhentao.mapper.CdzExceptionalRetroactionMapper;
import com.zhentao.mapper.CdzUserCouponMapper;
import com.zhentao.model.common.dtos.PageResponseResult;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.pojo.coupon.CdzCoupon;
import com.zhentao.model.common.pojo.coupon.CdzCouponCondition;
import com.zhentao.model.common.pojo.coupon.CdzExceptionalRetroaction;
import com.zhentao.model.common.pojo.coupon.CdzUserCoupon;
import com.zhentao.model.common.pojo.coupon.cdzdtos.CouponDTO;
import com.zhentao.model.common.pojo.coupon.cdzdtos.UserCouponDTO;
import com.zhentao.model.common.pojo.coupon.vo.CdzCouponVo;
import com.zhentao.model.common.pojo.users.Users;
import com.zhentao.model.common.pojo.users.param.UserBalanceParam;
import com.zhentao.service.ICdzCouponService;
import com.zhentao.userLocal.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mp
 * @since 2024-12-18
 */
@Service
public class CdzCouponServiceImpl extends ServiceImpl<CdzCouponMapper, CdzCoupon> implements ICdzCouponService {

    @Resource
    private CdzExceptionalRetroactionMapper exceptionalRetroactionMapper;
    @Autowired
    private UserApi userApi;
    @Resource
    private CdzCouponConditionMapper cdzCouponConditionMapper;
    @Override
    /**
     * @description: 分页查询优惠卷
     * @author: muhaoyang
     * @date: 2024/12/18 19:26
     * @param: [couponDTO]
     * @return: com.zhentao.model.common.dtos.ResponseResult
     **/
    public ResponseResult CouponPage(CouponDTO couponDTO) {
        Integer expireType = couponDTO.getExpireType();

//      分页配置
        IPage<CdzCoupon> page = new Page<>(couponDTO.getPageNum(), couponDTO.getPageSize());
//        进行判断
        LambdaQueryWrapper<CdzCoupon> wrapper = Wrappers.<CdzCoupon>lambdaQuery()
                .eq(CdzCoupon::getExpireType, expireType)
                .orderByDesc(CdzCoupon::getCreateTime)
                .eq(CdzCoupon::getStatus,1)
                ;
        this.page(page, wrapper);
        List<CdzCoupon> records = page.getRecords();
        for (int i = 0; i < records.size(); i++) {
            CdzCouponVo cdzCouponVo = new CdzCouponVo();
            CdzCoupon cdzCoupon = records.get(i);
//            获取vo对象,向前端返回
            BeanUtils.copyProperties(cdzCoupon, cdzCouponVo);
//            执行查询操作
            CdzCouponCondition cdzCouponCondition = cdzCouponConditionMapper.selectById(cdzCoupon.getConditionId());
//           设置值
            cdzCouponVo.setExceptionMessage(cdzCouponCondition.getCondition());
            cdzCouponVo.setCouponValue(cdzCouponCondition.getFaceValue());

            records.set(i, cdzCouponVo);
        }


        PageResponseResult result = new PageResponseResult(couponDTO.getPageNum(),couponDTO.getPageSize(), (int) page.getTotal());
        result.setData(records);
        return ResponseResult.okResult(result);
    }

    @Resource
    private CdzUserCouponMapper userCouponMapper;
    /**
     * @description:添加优惠卷
     * @author: muhaoyang
     * @date: 2024/12/19 9:40
     * @param: [couponId]
     * @return: com.zhentao.model.common.dtos.ResponseResult
     **/
    @Override
    public ResponseResult addCoupon(UserCouponDTO userCouponDTO) {
        Long userId = UserThreadLocalUtil.getUser();
//        获取当前用户
        Users user  = userApi.getUserInfo(userId);
//        判断用户是否拥有该优惠卷
        CdzUserCoupon userCoupon = userCouponMapper.selectOne(Wrappers.<CdzUserCoupon>lambdaQuery().eq(CdzUserCoupon::getCouponId, userCouponDTO.getCouponId()).eq(CdzUserCoupon::getUserId, userId));
        if (userCoupon != null) {
//            用户拥有该优惠卷
            return ResponseResult.errorResult(400,"您已拥有该优惠卷");
        }
        Integer couponId = userCouponDTO.getCouponId();
//        获取优惠卷信息
        CdzCoupon byId = this.getById(couponId);
//        判断优惠卷是否过期
        long time = byId.getEndTime().getTime();
//        获取当前时间
        long l = System.currentTimeMillis();
//        判断优惠卷到期时间是否小于当前时间
        if (time < l) {
//            优惠卷已过期
            byId.setStatus(1);
            this.updateById(byId);
            return ResponseResult.errorResult(400,"优惠卷已过期");
        }
        int point = Integer.parseInt(user.getPoint());
        if (point< byId.getPoint()) {
//            积分不足
            return ResponseResult.errorResult(400,"积分不足,最少需要："+byId.getPoint());
        }
        Integer times = byId.getTimes();
//        判断优惠卷是否有剩余
        if (times <= 0) {
            byId.setIsDel(0);
            this.updateById(byId);
            return ResponseResult.errorResult(400,"优惠卷被抢完了");
        }
//        执行添加
        CdzUserCoupon cdzUserCoupon = new CdzUserCoupon();
//        优惠卷id
        cdzUserCoupon.setCouponId(couponId);
//        用户id
        cdzUserCoupon.setUserId(user.getId());
//        不删除
        cdzUserCoupon.setIsDel(1);
//        可用
        cdzUserCoupon.setStatus(1);
//        有效期
        cdzUserCoupon.setPeriod(byId.getEndTime());
        userCouponMapper.insert(cdzUserCoupon);
//        执行添加完成后,减少库存
        byId.setTimes(times-1);
        this.updateById(byId);
//        扣减用户积分
        UserBalanceParam userBalanceParam = new UserBalanceParam();
        userBalanceParam.setUserId(user.getId());
        userBalanceParam.setPoint(userCouponDTO.getPoint());
        userApi.updatePonit(userBalanceParam);
        return ResponseResult.okResult(200,"添加成功");
    }
}
